/*****************************************************************************************
**  Author:jxx 2022
**  QQ:283591387
**完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
**常用示例见：http://v2.volcore.xyz/document/vueDev
**后台操作见：http://v2.volcore.xyz/document/netCoreDev
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "../goodsin_class/goodsInCom.vue"
// import { mapMutations } from "vuex";
import gridHeader from "@/components/print/selectTemplet.vue"
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    // ...mapMutations(
    //   ("salesContractMX", ["storeRemoveForm", "storeChangeForm"])
    // ),
    //下面这些方法可以保留也可以删除
    async onInit() {  //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;

      this.queryFields=['WHSE_no','CreateDate']
      this.textInline = false
      this.detailOptions.textInline = false
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]

      if (this.$route.path == "/q_overflow_voucher" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.WHSE_Id = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Voucher_sub',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    async onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      await this.detailOptions.buttons.splice(this.detailOptions.buttons.findIndex(item => item.name == "添加行"), 1)
      this.detailOptions.buttons.unshift({
        name: "报溢",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {

          if (this.rowschild&&this.$refs.detail.rowData.length) {
            this.rowschild.click()
          }
          // let form = {
          //   AuditStatus: 1
          // }
          // this.storeChangeForm(form);
          this.$store.commit("setTabelText", true)
          // const WHSE_Id_val = JSON.stringify(this.editFormFields.WHSE_Id)
          // if (WHSE_Id_val == "[]" || WHSE_Id_val == "null") {
          if (!this.editFormFields.WHSE_no) {
            this.base.ElMessageFn("请先选择报溢机构")
            return false;
          }
          this.$refs.modelHeader.detailOpen("报溢")
        }
      })
      this.detailOptions.columns.forEach(x => {
        if (x.field == 'WHSE_name') {
          x.filter = false
        }
      })
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_overflow_voucher" || this.rowAuditStatus != 0) return false;//|| !this.CreateUserBoole
        this.detailOptions.columns.forEach(item => {
          // if (item.field == "Tax_rate") {
          //   item.onChange = (e) => {
          //     // if (! +e.Overflow_price && e.Overflow_price != undefined) {
          //     //   row.Overflow_price_total_price = undefined
          //     //   // row.Tax_exclusive_overflow_price_total_price = undefined
          //     //   // row.Tax_exclusive_overflow_price = undefined
          //     //   this.base.ElMessageFn("报溢单价请输入有效数字")
          //     //   return
          //     // }
          //     if (! +e.Goods_num && e.Goods_num != undefined) {
          //       // row.Overflow_price_total_price = undefined
          //       // row.Tax_exclusive_overflow_price_total_price = undefined
          //       // row.Tax_exclusive_overflow_price = undefined
          //       this.base.ElMessageFn("数量请输入有效数字")
          //       return
          //     }
          //     // if (row.Overflow_price) {
          //     //   const num = row.Overflow_price / (1 + +e.Tax_rate)
          //     //   // row.Tax_exclusive_overflow_price = this.base.roundToFourDecimals(num)
          //     // }
          //     if (row.Goods_num) {// && row.Overflow_price
          //       // const num2 = (row.Goods_num * row.Overflow_price) / (1 + +e.Tax_rate)
          //       // row.Tax_exclusive_overflow_price_total_price = this.base.roundToFourDecimals(num2)
          //     }
          //   }
          // }
          if (item.field == "WHSE_name") {
            // this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_Id[this.editFormFields.WHSE_Id.length - 1])
            this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_no)
            //#region
            // let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.Goods_sub}`
            // item.bind.data.forEach(d => {
            //   d.hidden = true
            // })
            // this.http.post(selectUrl, {}, "").then(reslut => {
            //   item.bind.data.forEach(d => {
            //     d.hidden = true
            //   })
            //   // item.bind.data.forEach(d => {
            //   //   reslut.rows.forEach(j => {
            //   //     if (d.key == j.WHSE_no) {
            //   //       d.hidden = false
            //   //     }
            //   //   })
            //   // })
            //   item.bind.data.forEach(d => {
            //     reslut.forEach(j => {
            //       if (d.key == j.WHSE_no) {
            //         d.hidden = false
            //       }
            //     })
            //   })
            // })
            //#endregion

          }
        })

        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        this.rowschild = rows[0].childNodes[3]
        setTimeout(() => {
          //数量
          let testInputDom = rows[index].querySelectorAll("td")[6].querySelector("input")
          testInputDom.addEventListener("keyup", (e) => {

            if (!+e.target.value && e.target.value != undefined) {
              // row.Overflow_price_total_price = undefined
              // row.Tax_exclusive_overflow_price_total_price = undefined
              // row.Tax_exclusive_overflow_price = undefined
              this.base.ElMessageFn("数量请输入有效数字")
              return
            }
            // if (!+row.Overflow_price && row.Overflow_price != undefined) {
            //   row.Overflow_price_total_price = undefined
            //   row.Tax_exclusive_overflow_price_total_price = undefined
            //   row.Tax_exclusive_overflow_price = undefined
            //   this.base.ElMessageFn("报溢单价请输入有效数字")
            //   return
            // }
            // if (+e.target.value) {
            //   if (row.Overflow_price) {
            //     row.Overflow_price_total_price = row.Overflow_price * e.target.value
            //   }
            //   if (row.Tax_rate && row.Overflow_price) {
            //     const num1 = row.Overflow_price / (1 + +row.Tax_rate)
            //     const num2 = (e.target.value * row.Overflow_price) / (1 + +row.Tax_rate)
            //     row.Tax_exclusive_overflow_price = this.base.roundToFourDecimals(num1)
            //     row.Tax_exclusive_overflow_price_total_price = this.base.roundToFourDecimals(num2)
            //   }
            // }
            // else {
            //   row.Overflow_price_total_price = ""
            //   row.Tax_exclusive_overflow_price_total_price = ""
            //   row.Tax_exclusive_overflow_price = ""
            //   ElMessage.closeAll()
            //   ElMessage({
            //     message: '请出入数字',
            //     type: 'warning',
            //   })
            // }
          })
          //报溢单价
          // let testInputDom2 = rows[index].querySelectorAll("td")[10].querySelector("input")
          // testInputDom2.addEventListener("keyup", (e) => {
          //   if (!+e.target.value && e.target.value != undefined) {
          //     row.Overflow_price_total_price = undefined
          //     row.Tax_exclusive_overflow_price_total_price = undefined
          //     row.Tax_exclusive_overflow_price = undefined
          //     this.base.ElMessageFn("报溢单价请输入有效数字")
          //     return
          //   }
          //   if (!+row.Goods_num && row.Goods_num != undefined) {
          //     row.Overflow_price_total_price = undefined
          //     row.Tax_exclusive_overflow_price_total_price = undefined
          //     row.Tax_exclusive_overflow_price = undefined
          //     this.base.ElMessageFn("数量请输入有效数字")
          //     return
          //   }
          //   if (+e.target.value) {
          //     if (row.Goods_num) {
          //       row.Overflow_price_total_price = row.Goods_num * e.target.value
          //     }
          //     if (row.Tax_rate && row.Goods_num) {
          //       const num1 = e.target.value / (1 + +row.Tax_rate)
          //       const num2 = (e.target.value * row.Goods_num) / (1 + +row.Tax_rate)
          //       row.Tax_exclusive_overflow_price = this.base.roundToFourDecimals(num1)
          //       row.Tax_exclusive_overflow_price_total_price = this.base.roundToFourDecimals(num2)
          //     }
          //   }
          //   // else {
          //   //   row.Overflow_price_total_price = ""
          //   //   row.Tax_exclusive_overflow_price_total_price = ""
          //   //   row.Tax_exclusive_overflow_price = ""
          //   //   ElMessage.closeAll()
          //   //   ElMessage({
          //   //     message: '请出入数字',
          //   //     type: 'warning',
          //   //   })
          //   // }

          // })
        }, 0)
        return true
      }
    },
    WHSE_IdDisableFn() {
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == 'WHSE_no') {
            x.disabled = true
          }
        })
      })
    },
  async  searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_overflow_voucher" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Overflow_voucher",param)
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub || !dateState) {
        //   param.wheres = param.wheres.filter(item => item.name != "Overflow_voucher")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => { return x.AuditStatus == 1 });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    async addBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    async updateBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    detailRowClick({ row, column, event }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_overflow_voucher" || this.rowAuditStatus != 0) { return };//|| !this.CreateUserBoole
      if (column.property == "Goods_num"  || column.property == "Remark") {//|| column.property == "Overflow_price"
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            if (inpDom) {
              inpDom.focus()
            }
          }, 0)
        }
      }
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      try {
        if (rows.length == this.$refs.detail.rowData.length) {
          this.$store.commit("setWHSE_time", true)
          this.$store.commit("setWHSE_disabled", true)
          this.WHSE_Interval = setInterval(() => {
            console.log("WHSE_Interval", this.WHSE_Interval)
            this.editFormOptions.forEach(item => {
              item.forEach(x => {
                if (x.field == 'WHSE_no') {
                  if (this.$store.state.WHSE_disabled) {
                    x.disabled = true
                  } else {
                    x.disabled = false
                  }
                }
              })
            })
            if (!this.$store.state.WHSE_time) {
              clearInterval(this.WHSE_Interval)
              console.log("WHSE_Interval清除", this.WHSE_Interval)

            }
          }, 500)

        }
      } catch {
        console.log("删除catch",)
      }
      return true;
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      //数据创建人和当前用户
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_overflow_voucher" || this.rowAuditStatus != 0) {//|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      this.rowschild = null
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field != "Remark") {
            x.disabled = true
          } else {
            x.disabled = false
          }
          if (x.field == "WHSE_no") {
            const bool = !(this.currentAction == 'Add')
            x.disabled = bool
            // x.onChange = () => {
            //   if (this.rowschild) {
            //     this.rowschild.click()
            //   }
            // }
          }
          if (this.$route.path != "/q_overflow_voucher" || this.rowAuditStatus != 0) {//|| !this.CreateUserBoole
            x.disabled = true
          }
        })
      })
    },
    destroyed() {
      //2021.04.11增加vue页面销毁方法,路由必须设置keepLive:false，设置方法见：前端开发文档-》[禁用页面缓存keepAlive]
      //需要更新methods.js与ViewGird.vue文件 2021.04.11
      console.log("destroyed", this.WHSE_Interval)
      if (this.WHSE_Interval) {
        clearInterval(this.WHSE_Interval)
        this.WHSE_Interval = null
      }
    },
    testAdd(formData) {
      if(this.currentAction=="Add"){
        formData.mainData.Goods_num=0
      }
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn("请选择报溢机构")
        return false;
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0 )
      if (boole2) {
        this.base.ElMessageFn("明细表中数量不可为零")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中数量请填写有效正数")
        return false;
      }
      // let boole22 = formData.detailData.some(item => +item.Overflow_price === 0 )
      // if (boole22) {
      //   this.base.ElMessageFn("明细表中报溢单价不可为零")
      //   return false;
      // }
      // let boole1 = formData.detailData.some(item => item.Overflow_price == "" || item.Overflow_price == null || item.Overflow_price == undefined)
      // if (boole1) {
      //   this.base.ElMessageFn("明细表中请填写报溢单价")
      //   return false;
      // }
      // let boole33 = formData.detailData.every(item => +item.Overflow_price > 0 && +item.Overflow_price)
      // if (!boole33) {
      //   this.base.ElMessageFn("明细表中报溢单价请填写有效正数")
      //   return false;
      // }
      // let booleP3 = formData.detailData.every(item => item.WHSE_name )
      // if (!booleP3) {
      //   this.base.ElMessageFn("明细表中请选择库位")
      //   return false;
      // }
      // let booleP4 = formData.detailData.every(item => item.Tax_rate )
      // if (!booleP4) {
      //   this.base.ElMessageFn("明细表中请选择税率")
      //   return false;
      // }
      return true
    },
  }
};
export default extension;
